package com.angelhack.metrosocial.ui;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.angelhack.metrosocial.database.EstacionMetro;
import com.angelhack.metrosocial.database.MetroDB;
import com.angelhack.metrosocial.utils.Post;
import com.angelhack.metrosocial.utils.Utilities;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class Marcadores {
	
	GoogleMap mapa;
	Context context;
	MetroDB db;
	JSONArray datos;
	private ArrayList<MarkerOptions> markers = new ArrayList<MarkerOptions>();
	
	public Marcadores(final Context context,final GoogleMap mapa){
		
		this.context = context;
		this.mapa = mapa;
		
		db = new MetroDB(context);
		
		SegundoPlanoBuscar sp = new SegundoPlanoBuscar(context);
		sp.execute();
		
		//cargarMarcadores();
		mapa.setOnMarkerClickListener(new OnMarkerClickListener() {
		    public boolean onMarkerClick(Marker marker) {
		    //iniciamos intent 
		    	db.open();
		    	EstacionMetro est = db.getEstacionByName(marker.getTitle());
		    	Intent i = new Intent(context, ComentariosActivity.class);
		    	i.putExtra("id", est.getId());
		    	i.putExtra("title", est.getNombre() );
		    	i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		    	db.close();
		    	context.startActivity(i);
		        return true;
		    }
		});
	
		
	}
	
	public void cargarMarcadores(){
	
		for(int i = 0;i<datos.length();i++){
			db.open();	
			
			try {
				if(datos.getJSONObject(i).getInt("id_station")!=0){
					final EstacionMetro m = db.getEstacionById(datos.getJSONObject(i).getInt("id_station"));
					final int j = i;
					 Handler handler = new Handler();
					Runnable mark = new Runnable() {
						
						@Override
						public void run() {
							try {
								mostrarMarcador(m.getLinea(),m.getNombre(),m.getLatitud(),m.getLongitud(),datos.getJSONObject(j).getInt("sum(status)"));
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					};
					handler.post(mark);
					//mostrarMarcador(m.getLinea(),m.getNombre(),m.getLatitud(),m.getLongitud(),datos.getJSONObject(i).getInt("sum(status)"));
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		
		}
		db.close();
		
		mostrarLineas("1",Color.rgb(253,70,131));
		mostrarLineas("2",Color.rgb(37,54,247));
		mostrarLineas("3",Color.rgb(145,189,80));
		mostrarLineas("4",Color.rgb(85,200,218));
		mostrarLineas("5",Color.rgb(249, 246,45));
		mostrarLineas("6",Color.rgb(255, 20,20));
		mostrarLineas("7",Color.rgb(255, 149,20));
		mostrarLineas("8",Color.rgb(70,149,102));
		mostrarLineas("9",Color.rgb(139, 81,75));
		mostrarLineas("A",Color.rgb(193, 45,186));
		mostrarLineas("B",Color.rgb(129, 165,139));
		
	}
	
	private void mostrarMarcador(String linea,String nombreEstacion,double lat, double lng,int trafico)
	{
		
		//Display display = ((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

		//float scale = getResources().getDisplayMetrics().densityDpi;
		
		//Log.d("trafico","num: "+trafico);
		
		MarkerOptions marker= new MarkerOptions();
		
		MarkerOptions markerStatus= new MarkerOptions();
		
		markerStatus.position(new LatLng(lat, lng));
		markerStatus.title(nombreEstacion);
		
		marker.position(new LatLng(lat, lng));
		marker.title(nombreEstacion);
	
		Bitmap icon = null;
		Bitmap iconStatus = null;
		
		
		AssetManager assets = context.getResources().getAssets();
		
		try {
			
			if(trafico == 0)
				iconStatus = BitmapFactory.decodeStream(assets.open("otro"+File.separator+"circulo_verde"+".png"));
			else if(trafico == 1)
				iconStatus = BitmapFactory.decodeStream(assets.open("otro"+File.separator+"circulo_amarillo"+".png"));
			else if(trafico == 2)
				iconStatus = BitmapFactory.decodeStream(assets.open("otro"+File.separator+"circulo_rojo"+".png"));
			
			icon = BitmapFactory.decodeStream(assets.open("Linea_"+linea+File.separator+nombreEstacion+".png"));
			
	
		} catch (IOException e) {
			Log.e("error icon","error");
		}
		
		if(icon != null){
			
			
			
			icon = Bitmap.createScaledBitmap(icon,70,70,true);
			marker.icon(BitmapDescriptorFactory.fromBitmap(icon));
			
			mapa.addMarker(marker);
			
			markers.add(marker);
			
			
			
			
		
		}else{
			Log.i("nombre estacion",linea);
			Log.i("nombre mal",nombreEstacion);			
		}
		
		
		iconStatus = Bitmap.createScaledBitmap(iconStatus,75,75,true);
		markerStatus.icon(BitmapDescriptorFactory.fromBitmap(iconStatus));
		
		mapa.addMarker(markerStatus);

	    
	   
	    
	}
	
	/*private void mostrarLineas()
	{
	    //Dibujo con Lineas
	 
	    PolylineOptions lineas = new PolylineOptions();
	           
	    for(MarkerOptions m : markers){
			
			lineas.add(m.getPosition());
			
		}
	    
	    lineas.width(8);
	    lineas.color(Color.GREEN);
	 
	    mapa.addPolyline(lineas);
	}*/
	
	private void mostrarLineas(String linea,int color)
	{
	    //Dibujo con Lineas
	 
	    PolylineOptions lineas = new PolylineOptions();
	           
	    db.open();
		ArrayList<EstacionMetro> estaciones = (ArrayList<EstacionMetro>) db.getEstacionPorLinea(linea);
		db.close();
		
		for(EstacionMetro m : estaciones){
			
			lineas.add(new LatLng(m.getLatitud(),m.getLongitud()));
			
		}
	    
	    //lineas.add(markers.get(0).getPosition());
	    
	    lineas.width(4);
	    lineas.color(color);
	 
	    mapa.addPolyline(lineas);
	}
	
	public class SegundoPlanoBuscar extends AsyncTask<Void,Integer,Boolean>
	{
		
		
		Context context;
		private final ProgressDialog mDialog;
		
		
		public SegundoPlanoBuscar(Context context)
		{
			this.context = context;
		    Log.d("Hilo","construyendo hilo");
		 	mDialog = new ProgressDialog(context);
	        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	        mDialog.setCancelable(false);
	        //mDialog.show();
		}
		
		@SuppressWarnings({ "unchecked", "rawtypes" })
		@Override
		protected Boolean doInBackground(Void... params) {
			
			ArrayList parametros = new ArrayList();
			parametros.add("dato");
			parametros.add("dato");
			// Llamada a Servidor Web PHP
			try {
				Post post = new Post();
				datos = post.getServerData(parametros,Utilities.HTPP_POST_PETICION_SERVER);

				//Log.d("Json","cant"+datos.length());
				if (datos != null && datos.length() > 0) {
					
					//Toast.makeText(Multijugador.this,"prueba buscar ",Toast.LENGTH_LONG).show();
					JSONObject json_data = datos.getJSONObject(0);
					Log.d("JSON", "usuario: " + json_data.get("id_station"));
					Log.d("JSON", "usuario: " + json_data.get("sum(status)"));
					
					//String aux = json_data.getString("status");
					return true;
				}
			} catch (Exception e) {
				Log.d("Login", "error conectar servidor");
			}			
			
			return false;
		}
		
		protected void onProgressUpdate(Long... progress) {
	     //   int percent = (int)(100.0);
	        mDialog.setProgress(100);
	    }

	    @Override
	    protected void onPostExecute(Boolean result) {
	        mDialog.dismiss();
	        
	        Log.d("Servidor", "hilo terminado");
	        if(result)
	        {
	        	cargarMarcadores();
	        }else
	        {
	        	Toast.makeText(context, "Error al obtener la info del Servidor, Internet Wonky?",Toast.LENGTH_SHORT ).show();
	        }
	       
	    }
	}
	
	
	public class SegundoPlanoRapido extends AsyncTask<Void,Integer,Boolean>
	{
		
		Context context;
		private final ProgressDialog mDialog;
		public SegundoPlanoRapido(Context context)
		{
			this.context = context;
			
		    Log.d("Hilo","construyendo hilo");
		 	mDialog = new ProgressDialog(context);
	        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	        mDialog.setCancelable(false);
	        //mDialog.show();
		}
		
		@SuppressWarnings({ "unchecked", "rawtypes" })
		@Override
		protected Boolean doInBackground(Void... params) {
			
		
			ArrayList parametros = new ArrayList();
			parametros.add("id_station");
			parametros.add("dato");
			parametros.add("status");
			parametros.add("0");
			// Llamada a Servidor Web PHP
			try {
				Post post = new Post();
				datos = post.getServerData(parametros,
						"http://hacktom.com/insertar_estaciones.php");

							} catch (Exception e) {
				Log.d("Login", "error conectar servidor");
			}			
			return null;
		}
		
		
		protected void onProgressUpdate(Long... progress) {
	     //   int percent = (int)(100.0);
	        mDialog.setProgress(100);
	    }

	    @Override
	    protected void onPostExecute(Boolean result) {
	        mDialog.dismiss();
	        
	        Log.d("Servidor", "hilo terminado");
	       
	    }
		
	}
	
}
